
import functools
import time

from flask import Blueprint, request, jsonify, make_response
from flask_restful import Api,Resource
from flask import current_app as app
from uitils.comm import get_data
from db import db1
from uitils.acl import aci
from uitils.jwton import jwte
from uitils.redison import red


userbp = Blueprint('userbp',__name__)



@userbp.route('/login',methods=['POST'])
def login():
    data = get_data()
    # 用户账号与密码
    username = data['username']
    password = data['password']
    # 判断用户名与密码是否正确
    sql = "select * from users where name='{}' and password='{}'".format(username,password)
    res = db1.find(sql)
    if not res:
        # 不存在直接返回
        return jsonify({'code':200,'msg':'用户名或密码错误,请重新输入'})
    starttime = time.time()
    # 生成token
    data = {'data': {"username": res['name'], 'uid': res['id'], "iat": starttime, "exp": 3600}}
    token = jwte.jwt_en(data)
    # 获取用户页面权限
    # pagelist = aci.get_page_reslist(res['id'])
    # print(pagelist)
    # 获取接口页面权限
    interfacelist = aci.get_interface_reslist(res['id'])
    key = 'interfacelists'+str(res['id'])
    red.set_add(key,interfacelist)
    return jsonify({'code':200,'token':token,'pagelist':interfacelist,'userid':res['id'],'username':res['name'],'msg':'登录成功'})



def getdata(data):
    list = []
    idlist = []
    for i in data:
        id = i['pid']
        if id not in idlist:
            if id != None:
                list.append({'id':id,'name':i['pname'],'son':[]})
                idlist.append(id)
    # 遍历顶级列表,在遍历数据.把子类添加到顶级列表中
    for j,val in enumerate(list):
        for i in data:
            if val['id'] == i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list


@userbp.route('/getresources')
def getresources():
    # uid = request.args.get('userid')
    uid = 2
    time.sleep(2)
    data = aci.get_user_reslist(uid)
    res = getdata(data)
    return jsonify({'code':200,'list':res})


@userbp.route('/roles')
def roles():
    sql = "select * from roles"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@userbp.route('/resource')
def resource():
    id = request.args.get('id')
    if id:
        sql = 'select resource_id from role_resource where role_id={}'.format(id)
        res = db1.findall(sql)
        list = []
        for i in res:
            list.append(i['resource_id'])
    else:
        time.sleep(1)
        sql = 'select * from resources'
        list = db1.findall(sql)
    return jsonify({'code':200,'list':list})


@userbp.route('/setrole',methods=['GET','POST'])
def setsole():
    if request.method == 'POST':
        data = get_data()
        # 先删除已有的资源
        id = request.args.get('id')
        sql = 'delete from role_resource where role_id={}'.format(int(id))
        db1.update(sql)
        # 配置新的资源
        ids = []
        for i in data.values():
            ids.append(i)
        for i in ids:
            sql1 = 'insert into role_resource(role_id,resource_id) values({},{})'.format(int(id),i)
            db1.update(sql1)
        return jsonify({'code':200,'msg':'配置成功'})


@userbp.route('/ggg')
def ggg():
    uid = 2
    res = aci.get_user_reslist(uid)
    return jsonify({'list':res})
 #
 # and rr.role_id=ro.pid
@userbp.route('/getresource_pid',methods=['GET','POST'])
def getresource_pid():

    if request.method == 'POST':
        id = request.args.get('pid')
        time.sleep(1)
        sql = "select r.id,r.name as roname from resources as r left join role_resource as rr on r.id=rr.resource_id where rr.role_id={}".format(int(id))
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})
    else:
        time.sleep(1)
        pid = request.args.get('pid')
        sql1 = "select * from roles where pid={}".format(int(pid))
        res1 = db1.findall(sql1)
        return jsonify({'code': 200, 'list': res1})


@userbp.route('/getusers')
def getusers():
    sql = "select id,name,mobile from users"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})

@userbp.route('/user_role')
def user_role():
    uid = request.args.get('userid')
    roleid = request.args.get('rid')
    sql = "select * from user_role where user_id={}".format(int(uid))
    res = db1.find(sql)
    if res:
        sql1 = "select role_id2 from mutex where role_id1={}".format(int(res['role_id']))
        res1 = db1.findall(sql1)
        print(res1)
        list = []
        for i in res1:
            list.append(i['role_id2'])
        if int(roleid) in list:
            return jsonify({'code':10020,"msg":'角色互斥'})
        sql2 = "insert into user_role(role_id2) values({}) where user_id={}".format(int(roleid),int(uid))
        db1.update(sql2)
        return jsonify({'code':200,"msg":'添加成功'})
    else:
        sql2 = "insert into user_role(user_id,role_id1) values({})".format(int(uid), int(roleid))
        db1.update(sql2)
        return jsonify({'code': 200, "msg": '添加成功'})


import datetime
def timer(func):
    @functools.wraps(func)
    def decor(*args, **kwargs):
        token=request.headers['Token']
        myjwt=jwte
        num=myjwt.jwt_de(token)
        data = red.hash_get_all('abac')
        ip=request.remote_addr
        times = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
        for (key, value) in data.items():
            if key == 'ip':
                if str(value)!=str(ip):
                    return 'ip限制'
            if key=='time':
                starttime=eval(value)[0]
                end=eval(value)[1]
                if starttime>times and times>end:
                    return '时间限制'
            if key=='role':
                sql = "select role_id from users where id=%s" % num['data']['uid']
                roleid=db1.find(sql)
                if roleid['role_id'] !=int(value):
                    return '角色限制'
            if request.method != 'GET':
                return '请求方法限制'
        return  func( *args, **kwargs)
    return decor



import time
@userbp.route('/hash_shu',methods=['GET','POST'])
@timer
def hash_shu():
    red.hash_set('abac','ip','127.0.0.1')
    red.hash_set('abac','time',"['2020-10-15','2022-1-30']")
    red.hash_set('abac','role','1')
    data=red.hash_get_all('abac')
    times=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d")
    for (key,value) in data.items():
        if key=='time':
            print(eval(value)[0])
    return 'ok'









